/**********************************************************************************
  Snes9x - Portable Super Nintendo Entertainment System (TM) emulator.

  (c) Copyright 1996 - 2002  Gary Henderson (gary.henderson@ntlworld.com),
                             Jerremy Koot (jkoot@snes9x.com)

  (c) Copyright 2002 - 2004  Matthew Kendora

  (c) Copyright 2002 - 2005  Peter Bortas (peter@bortas.org)

  (c) Copyright 2004 - 2005  Joel Yliluoma (http://iki.fi/bisqwit/)

  (c) Copyright 2001 - 2006  John Weidman (jweidman@slip.net)

  (c) Copyright 2002 - 2006  funkyass (funkyass@spam.shaw.ca),
                             Kris Bleakley (codeviolation@hotmail.com)

  (c) Copyright 2002 - 2007  Brad Jorsch (anomie@users.sourceforge.net),
                             Nach (n-a-c-h@users.sourceforge.net),
                             zones (kasumitokoduck@yahoo.com)

  (c) Copyright 2006 - 2007  nitsuja


  BS-X C emulator code
  (c) Copyright 2005 - 2006  Dreamer Nom,
                             zones

  C4 x86 assembler and some C emulation code
  (c) Copyright 2000 - 2003  _Demo_ (_demo_@zsnes.com),
                             Nach,
                             zsKnight (zsknight@zsnes.com)

  C4 C++ code
  (c) Copyright 2003 - 2006  Brad Jorsch,
                             Nach

  DSP-1 emulator code
  (c) Copyright 1998 - 2006  _Demo_,
                             Andreas Naive (andreasnaive@gmail.com)
                             Gary Henderson,
                             Ivar (ivar@snes9x.com),
                             John Weidman,
                             Kris Bleakley,
                             Matthew Kendora,
                             Nach,
                             neviksti (neviksti@hotmail.com)

  DSP-2 emulator code
  (c) Copyright 2003         John Weidman,
                             Kris Bleakley,
                             Lord Nightmare (lord_nightmare@users.sourceforge.net),
                             Matthew Kendora,
                             neviksti


  DSP-3 emulator code
  (c) Copyright 2003 - 2006  John Weidman,
                             Kris Bleakley,
                             Lancer,
                             z80 gaiden

  DSP-4 emulator code
  (c) Copyright 2004 - 2006  Dreamer Nom,
                             John Weidman,
                             Kris Bleakley,
                             Nach,
                             z80 gaiden

  OBC1 emulator code
  (c) Copyright 2001 - 2004  zsKnight,
                             pagefault (pagefault@zsnes.com),
                             Kris Bleakley,
                             Ported from x86 assembler to C by sanmaiwashi

  SPC7110 and RTC C++ emulator code
  (c) Copyright 2002         Matthew Kendora with research by
                             zsKnight,
                             John Weidman,
                             Dark Force

  S-DD1 C emulator code
  (c) Copyright 2003         Brad Jorsch with research by
                             Andreas Naive,
                             John Weidman

  S-RTC C emulator code
  (c) Copyright 2001-2006    byuu,
                             John Weidman

  ST010 C++ emulator code
  (c) Copyright 2003         Feather,
                             John Weidman,
                             Kris Bleakley,
                             Matthew Kendora

  Super FX x86 assembler emulator code
  (c) Copyright 1998 - 2003  _Demo_,
                             pagefault,
                             zsKnight,

  Super FX C emulator code
  (c) Copyright 1997 - 1999  Ivar,
                             Gary Henderson,
                             John Weidman

  Sound DSP emulator code is derived from SNEeSe and OpenSPC:
  (c) Copyright 1998 - 2003  Brad Martin
  (c) Copyright 1998 - 2006  Charles Bilyue'

  SH assembler code partly based on x86 assembler code
  (c) Copyright 2002 - 2004  Marcus Comstedt (marcus@mc.pp.se)

  2xSaI filter
  (c) Copyright 1999 - 2001  Derek Liauw Kie Fa

  HQ2x, HQ3x, HQ4x filters
  (c) Copyright 2003         Maxim Stepin (maxim@hiend3d.com)

  Win32 GUI code
  (c) Copyright 2003 - 2006  blip,
                             funkyass,
                             Matthew Kendora,
                             Nach,
                             nitsuja

  Mac OS GUI code
  (c) Copyright 1998 - 2001  John Stiles
  (c) Copyright 2001 - 2007  zones


  Specific ports contains the works of other authors. See headers in
  individual files.


  Snes9x homepage: http://www.snes9x.com

  Permission to use, copy, modify and/or distribute Snes9x in both binary
  and source form, for non-commercial purposes, is hereby granted without
  fee, providing that this license information and copyright notice appear
  with all copies and any derived work.

  This software is provided 'as-is', without any express or implied
  warranty. In no event shall the authors be held liable for any damages
  arising from the use of this software or it's derivatives.

  Snes9x is freeware for PERSONAL USE only. Commercial users should
  seek permission of the copyright holders first. Commercial use includes,
  but is not limited to, charging money for Snes9x or software derived from
  Snes9x, including Snes9x or derivatives in commercial game bundles, and/or
  using Snes9x as a promotion for your commercial product.

  The copyright holders request that bug fixes and improvements to the code
  should be forwarded to them so everyone can benefit from the modifications
  in future versions.

  Super NES and Super Nintendo Entertainment System are trademarks of
  Nintendo Co., Limited and its subsidiary companies.
**********************************************************************************/

/**********************************************************************************
  Snes9x GTK Port
  
  (c) Copyright 2007 - 2008  Brandon Wright (bearoso@gmail.com)
**********************************************************************************/

#include <gdk/gdk.h>
#include "gtk_s9x.h"
#include "gtk_display.h"
#include "gtk_display_driver.h"
#include "gtk_display_driver_gtk.h"

#ifdef USE_OPENGL
#include "gtk_display_driver_opengl.h"
#endif

S9xDisplayDriver *driver;

thread_job_t job[NUM_THREADS];
GThreadPool *pool;

void
S9xColor16to32BGRA (void *src_buffer,
                    void *dst_buffer,
                    int src_pitch,
                    int dst_pitch,
                    int width, 
                    int height)
{
    for (register int y = 0; y < height; y++)
    {
        register uint32 *data = 
            (uint32 *) ((uint8 *) dst_buffer + y * dst_pitch);
        
        register uint16 *snes =
            (uint16 *) (((uint8 *) src_buffer) + y * src_pitch);
                    
        for (register int x = 0; x < width; x++)
        {
            uint32 pixel = *snes++;
            *data++ = (pixel & 0xf800) |
                      (pixel & 0x07e0) << 13 |
                      (pixel & 0x001f) << 27 |
                      0x00ff;
        }
    }
    
    return;
}

void
S9xColor16to24 (void *inbuf,
                void *outbuf,
                int input_pitch,
                int output_pitch,
                int width, 
                int height)
{
    for (register int y = 0; y < height; y++)
    {
        register uint8 *data = 
            (uint8 *) outbuf + y * output_pitch;
        
        register uint16 *snes =
            (uint16 *) (((uint8 *) inbuf) + y * input_pitch);
                    
        for (register int x = 0; x < width; x++)
        {
            uint32 pixel = *snes++;
            *data++ = (pixel >> 8) & 0xf8;
            *data++ = (pixel >> 3) & 0xfc;
            *data++ = (pixel << 3) & 0xf8;
        }
    }
    
    return;
}

void
S9xColor16to24andScale (void *inbuf,
                        void *outbuf,
                        int input_pitch,
                        int output_pitch,
                        int width, 
                        int height,
                        int dest_width,
                        int dest_height)
{
    register uint32 x_error, x_fraction;
    uint32 y_error = 0, y_fraction;
    int yy = 0;
    
    x_fraction = (width * 0x10000) / dest_width;
    y_fraction = (height * 0x10000) / dest_height;
    
    for (register int y = 0; y < dest_height; y++)
    {
        register uint8 *data = 
            (uint8 *) outbuf + y * output_pitch;
        
        register uint16 *snes =
            (uint16 *) (((uint8 *) inbuf) + 
            yy * input_pitch);
        
        y_error += y_fraction;
        
        while (y_error >= 0x10000)
        {
            yy++;
            y_error -= 0x10000;
        }
        
        x_error = 0;
                    
        for (register int x = 0; x < dest_width; x++)
        {
            uint32 pixel = *snes;
            *data++ = (pixel >> 8) & 0xf8;
            *data++ = (pixel >> 3) & 0xfc;
            *data++ = (pixel << 3) & 0xf8;
            
            x_error += x_fraction;
            
            while (x_error >= 0x10000)
            {
                snes++;
                x_error -= 0x10000;
            }
        }
    }
    
    return;
}

static void
thread_worker (gpointer data,
               gpointer user_data)
{
    thread_job_t *job = ((thread_job_t *) data);
    
    switch (job->operation_type)
    {
        case JOB_FILTER:
            S9xFilter (job->src_buffer,
                       job->src_pitch,
                       job->dst_buffer,
                       job->dst_pitch,
                       job->width,
                       job->height);
            break;
            
        case JOB_CONVERT:
            S9xColor16to24 (job->src_buffer,
                            job->dst_buffer,
                            job->src_pitch,
                            job->dst_pitch,
                            job->width, 
                            job->height);
            break;
            
        case JOB_CONVERT_BGRA:
            S9xColor16to32BGRA (job->src_buffer,
                                job->dst_buffer,
                                job->src_pitch,
                                job->dst_pitch,
                                job->width, 
                                job->height);
            break;            
            
        case JOB_SCALE_AND_CONVERT:
            S9xColor16to24andScale (job->src_buffer,
                                    job->dst_buffer,
                                    job->src_pitch,
                                    job->dst_pitch,
                                    job->width, 
                                    job->height,
                                    job->dst_width,
                                    job->dst_height);
            break;
    }
    
    job->complete = 1;

    return;
}

int
get_filter_scale (int width, int height)
{
    int scale = 1;
        
    switch (gui_config->scale_method)
    {
        case FILTER_SUPEREAGLE:
            scale = 2;
            break;
        case FILTER_2XSAI:
            scale = 2;
            break;
        case FILTER_SUPER2XSAI:
            scale = 2;
            break;
        case FILTER_HQ4X:
            if (((width * 4) <= S9xDisplayDriver::scaled_max_width) &&
                    ((height * 4) <= S9xDisplayDriver::scaled_max_height))
            {
                scale = 4;
                break;
            }
        case FILTER_HQ3X:
            if (width * 3 <= S9xDisplayDriver::scaled_max_width && 
                    height * 3 <= S9xDisplayDriver::scaled_max_height)
            {
                scale = 3;
                break;
            }
        case FILTER_HQ2X:
            scale = 2;
            break;
        case FILTER_EPX:
            scale = 2;
            break;
    }

    
    return scale;
}

void
S9xThreadedConvertAndScale (void *src_buffer, 
                            void *dst_buffer, 
                            int src_pitch, 
                            int dst_pitch,
                            int width,
                            int height,
                            int dst_width,
                            int dst_height)
{
    int i, flag;
    
    /* If the threadpool doesn't exist, create it */
    if (pool == NULL)
    {
        pool = g_thread_pool_new (thread_worker,
                                  NULL,
                                  NUM_THREADS - 1,
                                  TRUE,
                                  NULL);
    }
    
    for (i = 0; i < NUM_THREADS - 1; i++)
    {
        job[i].operation_type = JOB_SCALE_AND_CONVERT;
        job[i].src_buffer = 
            ((uint8 *) src_buffer) + (src_pitch * i * (height / NUM_THREADS));
        job[i].src_pitch = src_pitch;
        job[i].dst_buffer = 
            ((uint8 *) dst_buffer) + (dst_pitch * i * (dst_height / NUM_THREADS));
        job[i].dst_pitch = dst_pitch;
        job[i].width = width;
        job[i].height = height / NUM_THREADS;
        job[i].dst_width = dst_width;
        job[i].dst_height = dst_height / NUM_THREADS;
        job[i].complete = 0;
        
        g_thread_pool_push (pool, (gpointer) &(job[i]), NULL);
    }

    i = NUM_THREADS - 1;

    job[i].operation_type = JOB_SCALE_AND_CONVERT;
    job[i].src_buffer = 
        ((uint8 *) src_buffer) + (src_pitch * i * (height / NUM_THREADS));
    job[i].src_pitch = src_pitch;
    job[i].dst_buffer = 
        ((uint8 *) dst_buffer) + (dst_pitch * i * (dst_height / NUM_THREADS));
    job[i].dst_pitch = dst_pitch;
    job[i].width = width;
    job[i].height = 
        height - ((NUM_THREADS - 1) * (height / NUM_THREADS));
    job[i].dst_width = dst_width;
    job[i].dst_height = 
        dst_height - ((NUM_THREADS - 1) * (dst_height / NUM_THREADS));

    thread_worker ((gpointer) &(job[i]), NULL); 

    while (1)
    {
        flag = 1;
        for (i = 0; i < NUM_THREADS - 1; i++)
            flag = flag && job[i].complete;
        
        if (flag)
            break;
    }

    return;
}

void
S9xThreadedConvert (void *src_buffer, 
                    void *dst_buffer, 
                    int src_pitch, 
                    int dst_pitch,
                    int width,
                    int height)
{
    int i, flag;
    
    if (pool == NULL)
    {
        pool = g_thread_pool_new (thread_worker,
                                  NULL,
                                  NUM_THREADS - 1,
                                  TRUE,
                                  NULL);
    }
    
    for (i = 0; i < NUM_THREADS - 1; i++)
    {
        job[i].operation_type = JOB_CONVERT;
        job[i].src_buffer = 
            ((uint8 *) src_buffer) + (src_pitch * i * (height / NUM_THREADS));
        job[i].src_pitch = src_pitch;
        job[i].dst_buffer = 
            ((uint8 *) dst_buffer) + (dst_pitch * i * (height / NUM_THREADS));
        job[i].dst_pitch = dst_pitch;
        job[i].width = width;
        job[i].height = height / NUM_THREADS;
        job[i].complete = 0;

        g_thread_pool_push (pool, (gpointer) &(job[i]), NULL);
    }

    i = NUM_THREADS - 1;

    job[i].operation_type = JOB_CONVERT;
    job[i].src_buffer = 
        ((uint8 *) src_buffer) + (src_pitch * i * (height / NUM_THREADS));
    job[i].src_pitch = src_pitch;
    job[i].dst_buffer = 
        ((uint8 *) dst_buffer) + (dst_pitch * i * (height / NUM_THREADS));
    job[i].dst_pitch = dst_pitch;
    job[i].width = width;
    job[i].height = height - ((NUM_THREADS - 1) * (height / NUM_THREADS));

    thread_worker ((gpointer) &(job[i]), NULL);

    while (1)
    {
        flag = 1;
        for (i = 0; i < NUM_THREADS - 1; i++)
            flag = flag && job[i].complete;
        
        if (flag)
            break;
    }

    return;
}

void
S9xThreadedConvertBGRA (void *src_buffer, 
                        void *dst_buffer, 
                        int src_pitch, 
                        int dst_pitch,
                        int width,
                        int height)
{
    int i, flag;
    
    if (pool == NULL)
    {
        pool = g_thread_pool_new (thread_worker,
                                  NULL,
                                  NUM_THREADS - 1,
                                  TRUE,
                                  NULL);
    }
    
    for (i = 0; i < NUM_THREADS - 1; i++)
    {
        job[i].operation_type = JOB_CONVERT_BGRA;
        job[i].src_buffer = 
            ((uint8 *) src_buffer) + (src_pitch * i * (height / NUM_THREADS));
        job[i].src_pitch = src_pitch;
        job[i].dst_buffer = 
            ((uint8 *) dst_buffer) + (dst_pitch * i * (height / NUM_THREADS));
        job[i].dst_pitch = dst_pitch;
        job[i].width = width;
        job[i].height = height / NUM_THREADS;
        job[i].complete = 0;

        g_thread_pool_push (pool, (gpointer) &(job[i]), NULL);
    }

    i = NUM_THREADS - 1;

    job[i].operation_type = JOB_CONVERT_BGRA;
    job[i].src_buffer = 
        ((uint8 *) src_buffer) + (src_pitch * i * (height / NUM_THREADS));
    job[i].src_pitch = src_pitch;
    job[i].dst_buffer = 
        ((uint8 *) dst_buffer) + (dst_pitch * i * (height / NUM_THREADS));
    job[i].dst_pitch = dst_pitch;
    job[i].width = width;
    job[i].height = height - ((NUM_THREADS - 1) * (height / NUM_THREADS));

    thread_worker ((gpointer) &(job[i]), NULL);

    while (1)
    {
        flag = 1;
        for (i = 0; i < NUM_THREADS - 1; i++)
            flag = flag && job[i].complete;
        
        if (flag)
            break;
    }

    return;
}

int
S9xThreadedFilter (uint8 *src_buffer, 
                   int src_pitch, 
                   uint8 *dst_buffer, 
                   int dst_pitch,
                   int width,
                   int height)
{
    int i, scale, flag;
    
    scale = get_filter_scale (width, height);
    
    /* If the threadpool doesn't exist, create it */
    if (pool == NULL)
    {
        pool = g_thread_pool_new (thread_worker,
                                  NULL,
                                  NUM_THREADS - 1,
                                  TRUE,
                                  NULL);
    }
    
    for (i = 0; i < NUM_THREADS - 1; i++)
    {
        job[i].operation_type = JOB_FILTER;
        job[i].src_buffer = 
            src_buffer + (src_pitch * i * (height / NUM_THREADS));
        job[i].src_pitch = src_pitch;
        job[i].dst_buffer = 
            dst_buffer + (dst_pitch * i * scale * (height / NUM_THREADS));
        job[i].dst_pitch = dst_pitch;
        job[i].width = width;
        job[i].height = height / NUM_THREADS;
        job[i].complete = 0;

        g_thread_pool_push (pool, (gpointer) &(job[i]), NULL);
    }

    i = NUM_THREADS - 1;

    job[i].operation_type = JOB_FILTER;
    job[i].src_buffer = 
        src_buffer + (src_pitch * i * (height / NUM_THREADS));
    job[i].src_pitch = src_pitch;
    job[i].dst_buffer = 
        dst_buffer + (dst_pitch * i * scale * (height / NUM_THREADS));
    job[i].dst_pitch = dst_pitch;
    job[i].width = width;
    job[i].height = height - ((NUM_THREADS - 1) * (height / NUM_THREADS)); 

    thread_worker ((gpointer) &(job[i]), NULL);

    while (1)
    {
        flag = 1;
        for (i = 0; i < NUM_THREADS - 1; i++)
            flag = flag && job[i].complete;
        
        if (flag)
            break;
    }

    return scale;
}

int
S9xFilter (uint8 *src_buffer, 
           int src_pitch, 
           uint8 *dst_buffer, 
           int dst_pitch,
           int width,
           int height)
{    
    int scale = 1;
    
    switch (gui_config->scale_method)
    {
        case FILTER_SUPEREAGLE:
            Mac_SuperEagle (src_buffer, 
                            src_pitch,
                            dst_buffer,
                            dst_pitch,
                            width,
                            height);

            scale = 2;
            
            break;

        case FILTER_2XSAI:
            Mac_2xSaI (src_buffer,
                       src_pitch,
                       dst_buffer,
                       dst_pitch,
                       width,
                       height);

            scale = 2;
            
            break;

        case FILTER_SUPER2XSAI:
            Mac_Super2xSaI (src_buffer,
                            src_pitch,
                            dst_buffer,
                            dst_pitch,
                            width,
                            height);

            scale = 2;
            
            break;


        case FILTER_HQ4X:

            if (((width * 4) <= S9xDisplayDriver::scaled_max_width) &&
                    ((height * 4) <= S9xDisplayDriver::scaled_max_height))
            {
                HQ4X_16 (src_buffer,
                         src_pitch,
                         dst_buffer,
                         dst_pitch,
                         width,
                         height);

                scale = 4;
            
                break;
            }
            /* Fall back to 3x */

        case FILTER_HQ3X:

            if (width * 3 <= S9xDisplayDriver::scaled_max_width && 
                    height * 3 <= S9xDisplayDriver::scaled_max_height)
            {
                HQ3X_16 (src_buffer,
                         src_pitch,
                         dst_buffer,
                         dst_pitch,
                         width,
                         height);

                scale = 3;

                break;
            }
            /* Fall back to 2x */

        case FILTER_HQ2X:

            HQ2X_16 (src_buffer,
                     src_pitch,
                     dst_buffer,
                     dst_pitch,
                     width,
                     height);

            scale = 2;

            break;

        case FILTER_EPX:

            EPX_16_unsafe (src_buffer,
                           src_pitch,
                           dst_buffer,
                           dst_pitch,
                           width,
                           height);

            scale = 2;

            break;
    }
    
    return scale;
}


void
S9xDisplayRefresh (int width, int height)
{
    driver->refresh (width, height);
    
    return;
}

bool8 
S9xDeinitUpdate (int width, int height)
{   
    if (!Settings.Paused)
    {
        if (gui_config->overscan)
            height = (height > SNES_HEIGHT_EXTENDED) ? 
                         SNES_HEIGHT_EXTENDED * 2 :
                         SNES_HEIGHT_EXTENDED;
        else
            if (height > SNES_HEIGHT_EXTENDED)
                height = 448;
            else
                height = 224;
        
        GFX.Screen = driver->get_next_buffer ();
    }
    
    top_level->last_width = width;
    top_level->last_height = height;
    
    driver->update (width, height);
    
    return TRUE;
}

static void
S9xInitDriver (void)
{    
#ifdef USE_OPENGL
    if (gui_config->use_opengl)
    {
        driver = new S9xOpenGLDisplayDriver (top_level, gui_config);
    }
    else
#endif
    {
        driver = new S9xGTKDisplayDriver (top_level, gui_config);
    }

    driver->init ();
    
    pool = NULL;
    
    return;
}

void
S9xInitDisplay (int argc, char **argv)
{
    Settings.SupportHiRes = TRUE;
    S9xSetRenderPixelFormat (RGB565);
    InitLUTs ();    
    S9xInitDriver ();
    S9xGraphicsInit ();
    return;
}

void
S9xDisplayClearBuffers (void)
{
    driver->clear_buffers ();
    
    return;
}

void
S9xDeinitDisplay (void)
{
    driver->deinit ();
    delete driver;

    driver = NULL;
    GFX.Screen = NULL;
    
    if (pool)
        g_thread_pool_free (pool, FALSE, TRUE);
   
    return;
}

void
S9xReinitDisplay (void)
{
    S9xDeinitDisplay ();
    S9xInitDriver ();
    
    return;
}

bool8 
S9xContinueUpdate (int width, int height)
{
    return TRUE;
}

bool8 
S9xInitUpdate (void)
{
    return TRUE;
}

void 
S9xSetPalette (void)
{
    return;
}


